package com.five.producer;

import com.five.dto.CollectionDto;
import com.five.message.CollectMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.apache.rocketmq.spring.core.RocketMQTemplate;



@Service
@Slf4j
public class CollectTransactionProducer {

    @Autowired
    @Qualifier("addCollectRocketMQTemplate")
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送新增收藏的事务消息
     */
    public void sendAddCollectTxMsg(CollectionDto collectionDto) {
        Long readerId = collectionDto.getReaderId();
        Long novelId = collectionDto.getNovelId();
        // 1. 构建消息体
        CollectMessage msg = new CollectMessage();
        msg.setReaderId(readerId);
        msg.setNovelId(novelId);
        msg.setOperateType(1); // 1-新增

        // 2. 构建消息（将对象转换为JSON字符串）
        org.springframework.messaging.Message<CollectMessage> message = MessageBuilder.withPayload(msg).build();

        // 4. 发送事务消息
        rocketMQTemplate.sendMessageInTransaction("reader_topic:collect_add", message, collectionDto);
        log.info("新增收藏事务消息发送成功：readerId={}, novelId={}", readerId, novelId);
    }

    /**
     * 发送取消收藏的事务消息
     */
    public void sendCancelCollectTxMsg(CollectionDto collectionDto) {
        Long readerId = collectionDto.getReaderId();
        Long novelId = collectionDto.getNovelId();

        // 1. 构建消息体
        CollectMessage msg = new CollectMessage();
        msg.setReaderId(readerId);
        msg.setNovelId(novelId);
        msg.setOperateType(0); // 0-取消

        // 2. 构建消息（将对象转换为JSON字符串）
        org.springframework.messaging.Message<CollectMessage> message = MessageBuilder.withPayload(msg).build();

        // 4. 发送事务消息
        rocketMQTemplate.sendMessageInTransaction("reader_topic:collect_cancel", message, collectionDto);
        log.info("取消收藏事务消息发送成功：readerId={}, novelId={}", readerId, novelId);
    }
}